<template>
  <div>
    <el-tree
        :data="componentTreeData"
        show-checkbox
        node-key="id"
        default-expand-all
        @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>{{ formatComponentType(data) }}</span>
        </span>
      </template>
    </el-tree>
    <el-button type="primary" @click="handleConfirm">确定</el-button>
    <el-button type="success" @click="handleCancel">取消</el-button>
  </div>
</template>

<script lang="ts" setup>
import { watch, ref, inject } from "vue";
import { vFormSchemeKey } from '@/components/form/state.key';
import { InputComponents, ContainerComponents, TableComponents } from "../../../form/designer/data";

const formScheme = inject(vFormSchemeKey)!

interface Emits {
  (e: 'change', selectVariable: string): void
  (e: 'cancel'): void
}

const emits = defineEmits<Emits>()

const componentTreeData = ref([]);
const selectedId = ref('');

watch(() => formScheme, (val) => {
  componentTreeData.value = buildTree(formScheme.value, '');
  console.log('componentTreeData.value:' + JSON.stringify(componentTreeData.value))
}, { immediate: true, deep: true })

/**
 * 构造树结构,暂时只实现一层下级
 * @param schema
 * @param parentName
 */
function buildTree(schema: any, parentName: string): any[] {
  //搜索所有下级：非布局，展示，按钮组件
  let returnData = [];
  const childrens = schema.children || [];

  //遍历所有子节点
  for (let i = 0; i < childrens.length; i++) {
    if (childrens[i].category !== 'layout' && childrens[i].category !== 'display'
        && childrens[i].category !== 'button') {
      let tempNode: any = {};
      if (childrens[i].category == 'container' || childrens[i].component == 'ruoyi-ag-grid') {
        tempNode = {
          id: childrens[i].id,
          label: childrens[i].attrs.title,
          component: childrens[i].component,
        }
        returnData.push(tempNode)
        let childReturnData = [];
        if (childrens[i].component == 'ruoyi-ag-grid') {
          childReturnData = buildColumnDef(childrens[i]);
        } else {
          childReturnData = buildTree(childrens[i], childrens[i].name);
        }
        if (childReturnData.length > 0) {
          tempNode.children = childReturnData;
        }
      } else {
        returnData.push({
          id: childrens[i].id,
          label: childrens[i].formItemAttrs.label,
          component: childrens[i].component,
        })
      }
    } else {
      let childReturnData = buildTree(childrens[i], childrens[i].name);

      let tempNode = {
        id: childrens[i].id,
        label: childrens[i].formItemAttrs ? childrens[i].formItemAttrs.label : childrens[i].category,
        component: childrens[i].component,
        children: []
      };
      if (childReturnData.length > 0) {
        tempNode.children = childReturnData;
      }
      returnData.push(tempNode)
    }
  }
  return returnData;
}

/**
 * 构造指定表的列列表
 * @param agGrid
 */
function buildColumnDef(agGrid: any) {
  //循环表格字段列表
  let columnDef = [];

  for (let i = 0; i < agGrid.attrs.columnDefs.length; i++) {
    let tempNode = {
      id: agGrid.attrs.columnDefs[i].field,
      label: agGrid.attrs.columnDefs[i].headerName,
      component: 'ruoyi-ag-grid-field',
    }
    columnDef.push(tempNode)
  }
  return columnDef;
}

/**
 * 单击某个节点
 * @param data
 */
function handleNodeClick(data: any) {
  selectedId.value = data.id;
  console.log('handleNodeClick:' + selectedId.value)
}

/**
 *  单击确认按钮
 */
function handleConfirm() {
  console.log('handleConfirm:' + selectedId.value)
  emits('change', selectedId.value)
}

/**
 *  单击取消按钮
 */
function handleCancel() {
  emits('cancel')
}

/**
 * 翻译组件类型
 * @param data
 * @returns {*|string}
 */
function formatComponentType(data: any) {
  // console.log('row.component:'+row.component)
  // console.log('InputComponents:'+JSON.stringify(InputComponents))
  for (let i = 0; i < InputComponents.length; i++) {
    if (data.component === InputComponents[i].component) {
      return InputComponents[i].title;
    }
  }
  for (let i = 0; i < ContainerComponents.length; i++) {
    if (data.component === ContainerComponents[i].component) {
      return ContainerComponents[i].title;
    }
  }
  for (let i = 0; i < TableComponents.length; i++) {
    if (data.component === TableComponents[i].component) {
      return TableComponents[i].title;
    }
  }
  if (data.component === 'ruoyi-ag-grid-field') {
    return '列';
  }
  return '';
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-tree-node span:last-child {
  margin-left: 20px;
  color: #999;
}
</style>
